<template>
  <div ref="cesiumContainer" class="cesium-container"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps } from 'vue'
import * as Cesium from 'cesium'

// Props
const props = defineProps({
  mapboxToken: {
    type: String,
    default: ''
  },
  googleMapUrl: {
    type: String,
    default: 'https://www.servicetrial.com/xq/yndl/terrain/dali_map/{z}/{x}/{y}.jpg'
  },
  enableDebug: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['map-ready', 'tile-loaded', 'tile-error'])

// Refs
const cesiumContainer = ref(null)

// Variables
let viewer = null
let googleMapProvider = null

// Cesium Ion Token (如果需要)
// const cesiumIonToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhODg2OTQyOC03YWNiLTRkNGMtYWMxMi1mYjcwMTViOTBiZDkiLCJpZCI6MTk0NzksInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1NzU1OTgyMjN9.It5qL2PBTwwsumH_PTrqFdFwkRaNPsHJtWJOeEcVQXE'

/**
 * 创建Google地图瓦片提供者
 * 使用GeographicTilingScheme指定WGS84坐标系
 * 通过customTags解决切片级别偏移问题（Google从1开始，Cesium从0开始）
 */
const createGoogleMapProvider = () => {
  try {
    // 清理URL，移除可能的@符号
    let cleanUrl = props.googleMapUrl.trim();
    if (cleanUrl.startsWith('@')) {
      cleanUrl = cleanUrl.substring(1);
    }

    // 创建自定义的瓦片提供者
    googleMapProvider = new Cesium.UrlTemplateImageryProvider({
      url: 'https://www.servicetrial.com/xq/yndl/terrain/dali_map/{z}/{x}/{y}.jpg',
      // 使用地理坐标系 (WGS84)
      tilingScheme: new Cesium.GeographicTilingScheme({
        numberOfLevelZeroTilesX: 2,
        numberOfLevelZeroTilesY: 1
      }),
      // 设置瓦片大小
      tileWidth: 256,
      tileHeight: 256,
      // 设置最大缩放级别
      maximumLevel: 18,
      // 设置最小缩放级别
      minimumLevel: 0,
      // 解决切片级别偏移问题：Google切片从1开始，Cesium从0开始
      customTags: {
        z: function (imageryProvider, x, y, level) {
          // 将Cesium的level（从0开始）转换为Google的level（从1开始）
          const adjustedLevel = level + 1;
          if (props.enableDebug && Math.random() < 0.01) { // 只打印1%的请求避免日志过多
            console.log(`瓦片请求: z=${adjustedLevel}, x=${x}, y=${y}, 原始level=${level}`);
          }
          return adjustedLevel;
        },
        x: function (imageryProvider, x, y, level) {
          return x;
        },
        y: function (imageryProvider, x, y, level) {
          return y;
        }
      },
      // 设置请求头
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
      },
      // 启用跨域请求
      enablePickFeatures: false,
      // 添加错误处理
      errorEvent: new Cesium.Event()
    });

    // 监听错误事件
    if (googleMapProvider.errorEvent) {
      googleMapProvider.errorEvent.addEventListener((error) => {
        console.error('瓦片加载错误:', error);
        emit('tile-error', error);
      });
    }

    // 调试信息
    if (props.enableDebug) {
      console.log('Google地图瓦片提供者已创建');
      console.log('原始URL:', props.googleMapUrl);
      console.log('清理后URL:', cleanUrl);
      console.log('瓦片提供者:', googleMapProvider);
      console.log('坐标系:', googleMapProvider.tilingScheme.constructor.name);

      // 测试一个具体的瓦片URL
      const testUrl = cleanUrl
        .replace('{z}', '10')
        .replace('{x}', '100')
        .replace('{y}', '200');
      console.log('测试瓦片URL:', testUrl);
    }

    return googleMapProvider;
  } catch (error) {
    console.error('创建Google地图提供者失败:', error);
    emit('tile-error', error);
    return null;
  }
}

/**
 * 初始化Cesium viewer
 */
const initializeCesium = () => {
  try {
    // 设置 Cesium Ion Token
    // if (cesiumIonToken) {
    //   Cesium.Ion.defaultAccessToken = cesiumIonToken
    // }

    // 创建 Viewer - 关键：禁用默认的基础图层
    viewer = new Cesium.Viewer(cesiumContainer.value, {
      animation: false,
      baseLayerPicker: false, // 禁用基础图层选择器
      fullscreenButton: true,
      geocoder: false, // 禁用地理编码器避免使用默认服务
      homeButton: true,
      infoBox: true,
      sceneModePicker: true,
      selectionIndicator: true,
      timeline: false,
      navigationHelpButton: false,
      scene3DOnly: false,
      // 不设置imageryProvider，稍后手动添加
      imageryProvider: false, // 禁用默认图像提供者
      terrainProvider: undefined, // 禁用地形
      orderIndependentTranslucency: false,
      contextOptions: {
        webgl: {
          alpha: false,
          antialias: true,
          preserveDrawingBuffer: true,
          powerPreference: "high-performance"
        }
      },
      useBrowserRecommendedResolution: false,
      resolutionScale: window.devicePixelRatio || 1
    })

    // 添加网络请求拦截器
    if (props.enableDebug) {
      // 保存原始的 fetch 方法
      const originalFetch = window.fetch;

      // 重写 fetch 方法来监控请求
      window.fetch = function (url, options) {
        if (typeof url === 'string') {
          if (url.includes('servicetrial.com')) {
            console.log('🌐 检测到瓦片请求:', url);
            console.log('请求选项:', options);
          }
          // 监控所有瓦片相关请求
          if (url.includes('tiles') || url.includes('.jpg') || url.includes('.png') || url.includes('virtualearth')) {
            console.log('🔍 所有瓦片请求:', url);
          }
        }
        return originalFetch.apply(this, arguments);
      };

      // 同时监控 XMLHttpRequest
      const originalXHROpen = XMLHttpRequest.prototype.open;
      XMLHttpRequest.prototype.open = function (method, url) {
        if (typeof url === 'string') {
          if (url.includes('servicetrial.com')) {
            console.log('🌐 XHR 瓦片请求:', url);
          }
          // 监控所有瓦片相关请求
          if (url.includes('tiles') || url.includes('.jpg') || url.includes('.png') || url.includes('virtualearth')) {
            console.log('🔍 XHR 所有瓦片请求:', url);
          }
        }
        return originalXHROpen.apply(this, arguments);
      };
    }

    // 创建Google地图瓦片提供者
    const googleProvider = createGoogleMapProvider();
    if (!googleProvider) {
      throw new Error('无法创建Google地图瓦片提供者');
    }


    // 清除所有默认的图像图层
    viewer.imageryLayers.removeAll();

    // 添加我们自定义的Google地图图层
    const googleLayer = viewer.imageryLayers.addImageryProvider(googleProvider);

    if (props.enableDebug) {
      console.log('已添加Google地图图层:', googleLayer);
      console.log('当前图像图层数量:', viewer.imageryLayers.length);
    }

    // 设置初始视角到大理地区（根据URL中的dali_map推测）
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(100.2667, 25.6069, 50000), // 大理市坐标
      orientation: {
        heading: 0.0,
        pitch: -Cesium.Math.PI_OVER_TWO,
        roll: 0.0
      }
    })

    // 隐藏Cesium信用信息
    viewer.cesiumWidget.creditContainer.style.display = 'none'

    // 优化渲染设置
    viewer.scene.postProcessStages.fxaa.enabled = true
    viewer.scene.globe.enableLighting = false
    viewer.scene.highDynamicRange = false
    viewer.scene.globe.maximumScreenSpaceError = 1
    viewer.scene.globe.tileCacheSize = 100

    // 优化画布设置
    const canvas = viewer.scene.canvas
    canvas.style.imageRendering = 'auto'
    canvas.style.webkitFontSmoothing = 'antialiased'
    canvas.style.mozOsxFontSmoothing = 'grayscale'

    // 添加瓦片加载事件监听
    if (props.enableDebug) {
      viewer.scene.globe.tileLoadProgressEvent.addEventListener((queuedTileCount) => {
        console.log('瓦片加载进度:', queuedTileCount);
        if (queuedTileCount === 0) {
          console.log('所有瓦片加载完成');
          emit('tile-loaded', {
            message: '所有瓦片加载完成',
            queuedTileCount: queuedTileCount
          });
        }
      });

      // 监控图像图层的变化
      viewer.imageryLayers.layerAdded.addEventListener((layer) => {
        console.log('图像图层已添加:', layer);
      });

      viewer.imageryLayers.layerRemoved.addEventListener((layer) => {
        console.log('图像图层已移除:', layer);
      });
    }

    // 发射地图就绪事件
    emit('map-ready', {
      viewer: viewer,
      provider: googleProvider
    });

    console.log('Cesium初始化完成，Google离线地图加载成功');

  } catch (error) {
    console.error('Cesium初始化失败:', error);
    emit('tile-error', error);
  }
}

/**
 * 强制刷新瓦片
 */
const forceRefreshTiles = () => {
  if (viewer && viewer.imageryLayers.length > 0) {
    console.log('强制刷新瓦片...');
    const layer = viewer.imageryLayers.get(0);
    if (layer && layer.imageryProvider) {
      // 强制重新加载瓦片
      viewer.scene.globe.tilesLoaded = false;
      viewer.scene.requestRender();

      // 缩放到合适的级别来触发瓦片加载
      viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(100.2667, 25.6069, 10000),
        orientation: {
          heading: 0.0,
          pitch: -Cesium.Math.PI_OVER_TWO,
          roll: 0.0
        }
      });

      console.log('瓦片刷新完成');
    }
  }
}

/**
 * 切换到指定位置
 */
const flyToPosition = (longitude, latitude, height = 10000) => {
  if (viewer) {
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
      duration: 2.0
    });

    // 飞行完成后强制刷新瓦片
    setTimeout(() => {
      forceRefreshTiles();
    }, 2500);
  }
}

/**
 * 设置地图可见性
 */
const setMapVisibility = (visible) => {
  if (viewer && viewer.imageryLayers.length > 0) {
    viewer.imageryLayers.get(0).show = visible;
  }
}

/**
 * 获取当前相机位置
 */
const getCurrentCameraPosition = () => {
  if (viewer) {
    const position = viewer.camera.positionCartographic;
    return {
      longitude: Cesium.Math.toDegrees(position.longitude),
      latitude: Cesium.Math.toDegrees(position.latitude),
      height: position.height
    };
  }
  return null;
}

/**
 * 添加自定义图层
 */
const addImageryLayer = (provider, options = {}) => {
  if (viewer) {
    const layer = viewer.imageryLayers.addImageryProvider(provider, options);
    return layer;
  }
  return null;
}

/**
 * 移除图层
 */
const removeImageryLayer = (layer) => {
  if (viewer && layer) {
    viewer.imageryLayers.remove(layer);
  }
}

// 生命周期钩子
onMounted(() => {
  initializeCesium()
})

onUnmounted(() => {
  if (viewer) {
    viewer.destroy()
  }
})

// 暴露方法给父组件
defineExpose({
  flyToPosition,
  setMapVisibility,
  getCurrentCameraPosition,
  addImageryLayer,
  removeImageryLayer,
  forceRefreshTiles,
  viewer: () => viewer
})
</script>

<style scoped>
.cesium-container {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
  font-family: sans-serif;
}

/* 隐藏Cesium的默认UI元素 */
:deep(.cesium-viewer-bottom) {
  display: none;
}

/* 自定义信息框样式 */
:deep(.cesium-infoBox) {
  background: rgba(42, 42, 42, 0.9);
  color: white;
  border: 1px solid #555;
}

:deep(.cesium-infoBox-title) {
  background: #333;
  color: #4fc3f7;
}

/* 自定义控件样式 */
:deep(.cesium-button) {
  background: rgba(42, 42, 42, 0.8);
  color: white;
  border: 1px solid #555;
}

:deep(.cesium-button:hover) {
  background: rgba(66, 165, 245, 0.8);
}

/* 工具栏样式 */
:deep(.cesium-toolbar) {
  background: rgba(42, 42, 42, 0.8);
}

/* 地理编码器样式 */
:deep(.cesium-geocoder-searchButton) {
  background: rgba(42, 42, 42, 0.8);
  color: white;
}

:deep(.cesium-geocoder-input) {
  background: rgba(42, 42, 42, 0.8);
  color: white;
  border: 1px solid #555;
}

/* 基础图层选择器样式 */
:deep(.cesium-baseLayerPicker-dropDown) {
  background: rgba(42, 42, 42, 0.9);
  color: white;
  border: 1px solid #555;
}
</style>
